﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using NPOI.HSSF.UserModel;
using System.IO;
using System.Threading;

namespace HermesWinForm
{
    public partial class ImportOrders : Form
    {
        List<OrdersServiceReference.Orders> ErrList;
        bool SelectFile = false;
        bool SelectSite = false;
        bool SelectStore = false;

        Thread threadImport;

        public ImportOrders()
        {
            InitializeComponent();
        }

        private void btnBrowser_Click(object sender, EventArgs e)
        {
            DialogResult result = openOrdersFile.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.OK && openOrdersFile.CheckFileExists && openOrdersFile.CheckPathExists)
            {
                txtFilePath.Text = openOrdersFile.FileName;

                SelectFile = true;
                //btnHKPOST.Enabled = true;
            }
            else
            {
                MessageBox.Show("打开文件失败。");
                SelectFile = false;
            }


            if (SelectSite && SelectFile && SelectStore)
            {
                btnImport.Enabled = true;
            }
            else
            {
                btnImport.Enabled = false;
            }
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            ErrList = new List<OrdersServiceReference.Orders>();

         
            string message = string.Empty;
            string fileName = string.Empty;
            fileName = txtFilePath.Text;


            List<OrdersServiceReference.Orders> importOrdersList = new List<OrdersServiceReference.Orders>();
            if (cbSites.SelectedItem.ToString() == "Amazon")
            {
                importOrdersList = GetOrdersFormAmazonExcel(fileName, ref message, "liutao");
            }
            else
            {
                MessageBox.Show("the Site order data is not support");
                return;
            }
            

            if (!string.IsNullOrEmpty(message))
            {
                richtxtMessage.Text = message;
                return;
            }

            OrdersServiceReference.SalesOrderSoapClient orderClient = new OrdersServiceReference.SalesOrderSoapClient();

            richtxtMessage.Text = string.Empty;
            btnImport.Enabled = false;
            btnBrowser.Enabled = false;
            btnExportErrorOrders.Visible = false;

            threadImport = new Thread(delegate()
            {
                int i = 1;
                foreach (OrdersServiceReference.Orders temp in importOrdersList)
                {
                    StringBuilder sbMessage = new StringBuilder();
                    if (this.InvokeRequired)
                    {
                        this.Invoke(new MethodInvoker(delegate()
                        {
                            sbMessage.AppendLine("---------------------------");
                            sbMessage.AppendLine("正在处理第" + i + "条数据：");
                        }));
                    }
                    try
                    {

                        message = orderClient.InsertOrder(temp);
                        if (this.InvokeRequired)
                        {
                            this.Invoke(new MethodInvoker(delegate()
                            {
                                if (message == "0")
                                    message = "导入成功!";
                                else
                                {
                                    temp.Notes = message;
                                    ErrList.Add(temp);
                                }
                                sbMessage.AppendLine("处理结果：" + message);
                                richtxtMessage.AppendText(sbMessage.ToString());
                            }));
                        }
                    }
                    catch (System.Exception ex)
                    {
                        if (this.InvokeRequired)
                        {
                            this.Invoke(new MethodInvoker(delegate()
                            {
                                temp.Notes = message;
                                ErrList.Add(temp);
                                sbMessage.AppendLine("处理结果：" + ex.Message);
                                richtxtMessage.AppendText(sbMessage.ToString());
                            }));
                        }
                    }

                    i++;
                }

                if (this.InvokeRequired)
                {
                    this.Invoke(new MethodInvoker(delegate()
                    {
                        StringBuilder sbMessage = new StringBuilder();
                        sbMessage.AppendLine("---------------------------");
                        sbMessage.AppendLine(string.Format("全部处理完成，总共处理{0}条数据，{1}条数据导入成功，{2}条数据导入失败。", importOrdersList.Count, importOrdersList.Count - ErrList.Count, ErrList.Count));
                        richtxtMessage.AppendText(sbMessage.ToString());

                        btnBrowser.Enabled = true;
                        if (ErrList.Count > 0)
                        {
                            btnExportErrorOrders.Visible = true;
                        }
                    }));
                }
            });

            threadImport.Start();
        }

        private List<OrdersServiceReference.Orders> GetOrdersFormAmazonExcel(string fileName, ref string message, string importUser)
        {
            List<OrdersServiceReference.Orders> ordersList = new List<OrdersServiceReference.Orders>();
            HSSFWorkbook workbook = null;
            StringBuilder sbMessage = new StringBuilder();

            try
            {
                using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    workbook = new HSSFWorkbook(fileStream);
                }
            }
            catch (Exception ex)
            {
                message = "文件读取发生问题：" + ex.ToString();
            }
            if (!string.IsNullOrEmpty(message))
            {
                return null;
            }

            HSSFSheet sheet = workbook.GetSheetAt(0);
            System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
            int rowNumber = -1;

            List<string> orderIds = new List<string>();

            Dictionary<string, List<OrdersServiceReference.OrderLines>> indexlines = new Dictionary<string, List<OrdersServiceReference.OrderLines>>();

            while (rows.MoveNext())
            {
                HSSFRow row = (HSSFRow)rows.Current;
                if (rowNumber == -1)
                {
                    //if (!DateTime.TryParse(row.GetCell(1).ToString(), out orderTime))
                    //{
                    //    message = "订单时间格式错误：" + row.GetCell(1).ToString();
                    //    break;
                    //}

                    //customerCode = row.GetCell(3).StringCellValue;
                    rowNumber++;
                    continue;
                }

                if (row.GetCell(0).CellType == HSSFCellType.BLANK)
                {
                    break;
                }

                DateTime orderTime = DateTime.MinValue;
                string customerCode = string.Empty;

                string id = row.GetCell(0).ToString().Trim();

                

                if (!indexlines.ContainsKey(id))
                {
                    orderIds.Add(id);

                    OrdersServiceReference.Orders orders = new OrdersServiceReference.Orders();


                    orders.OrderNumber = row.GetCell(0).ToString().Trim();
                    orders.SiteID = SiteInfo.GetSiteID("Amazon");//AMAZON
                    orders.ImportBy = importUser;
                    //orders.order_item_id = row.GetCell(1).ToString().Trim();
                    orders.OrderTime = DateTime.Parse(row.GetCell(2).ToString().Trim());
                    //orders.payments_date = row.GetCell(3).ToString().Trim();
                    orders.Email = row.GetCell(7).ToString().Trim();
                    orders.Contact = row.GetCell(8).ToString().Trim();
                    if (row.GetCell(9) != null)
                    {
                        orders.Phone = row.GetCell(9).ToString().Trim();
                    }
                    //orders.OrderLines = new List<OrdersServiceReference.OrderLines>();
                    List<OrdersServiceReference.OrderLines> lines = new List<OrdersServiceReference.OrderLines>();
                    OrdersServiceReference.OrderLines line = new OrdersServiceReference.OrderLines();

                    line.SKU = row.GetCell(10).ToString().Trim();
                    //line.pproduct_name = row.GetCell(11).ToString().Trim();
                    line.QTY = int.Parse(row.GetCell(14).ToString().Trim());
                    line.OrderNUmber = orders.OrderNumber;
                    lines.Add(line);
                    indexlines.Add(id,lines);


                    //orders.ship_service_level = row.GetCell(15).ToString().Trim();
                    orders.Contact = row.GetCell(16).ToString().Trim();


                    String address = row.GetCell(17).ToString().Trim();
                    if (row.GetCell(18) == null)
                    {
                        //address += " ";
                    }
                    else
                    {
                        address += " " + row.GetCell(18).ToString().Trim();
                    }
                    if (row.GetCell(19) == null)
                    {
                        //address += " ";
                    }
                    else
                    {
                        address += " " + row.GetCell(19).ToString().Trim();
                    }
                    orders.Street = address;

                    orders.City = row.GetCell(20).ToString().Trim();
                    orders.Province = row.GetCell(21).ToString().Trim();
                    orders.Postcode = row.GetCell(22).ToString().Trim();
                    orders.Country = row.GetCell(23).ToString().Trim();

                    ordersList.Add(orders);

                }
                else
                {
                    var temp = indexlines[id];

                    if (temp != null && temp.Count > 0)
                    {
                        
                        OrdersServiceReference.OrderLines line = new OrdersServiceReference.OrderLines();

                        line.SKU = row.GetCell(10).ToString().Trim();
                        //line.pproduct_name = row.GetCell(11).ToString().Trim();
                        line.QTY = int.Parse(row.GetCell(14).ToString().Trim());
                        line.OrderNUmber = id;
                        temp.Add(line);
                        indexlines[id] = temp;
                    }

                }
            }

            foreach (OrdersServiceReference.Orders order in ordersList)
            {
                order.OrderLines = indexlines[order.OrderNumber].ToArray();
            }

            return ordersList;
        }

        private void ImportOrders_Load(object sender, EventArgs e)
        {
            string[] siteNames = SiteInfo.GetSiteName();
            for (int i = 0; i < siteNames.Length; ++i)
            {
                cbSites.Items.Insert(i, siteNames[i]);
            }

            cbStore.Enabled = false;
        }

        private void cbSites_SelectedIndexChanged(object sender, EventArgs e)
        {



            if (cbSites.SelectedItem.ToString() != "")
            {
                SelectSite = true;
                cbStore.Enabled = true;

                for (int i = cbStore.Items.Count-1; i >=0; --i)
                {
                    cbStore.Items.RemoveAt(i);
                }

                string[] storeNames = StoreInfo.GetStoreName();
                int j = 0;
                for (int i = 0; i < storeNames.Length; ++i)
                {
                    if (storeNames[i].Contains(cbSites.SelectedItem.ToString()))
                    {
                        cbStore.Items.Insert(j, storeNames[i]);
                        ++j;
                    }
                }

                if (cbStore.SelectedItem !=null&& cbStore.SelectedItem.ToString() != "")
                {
                    SelectStore = true;

                }
                else
                {
                    SelectStore = false;
                }
                
            }
            else
            {
                SelectSite = false;
                cbStore.Enabled = false;
            }

            if (SelectSite && SelectFile && SelectStore)
            {
                btnImport.Enabled = true;
            }
            else
            {
                btnImport.Enabled = false;
            }
        }

        private void btnExportErrorOrders_Click(object sender, EventArgs e)
        {
            DialogResult result = saveOrdersFile.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                ExportErrorOrders(saveOrdersFile.FileName);
            }
            else
            {
                MessageBox.Show("选择的保存文件失败。");
            }

        }

        private void ExportErrorOrders(string fileName)
        {
            //创建xls文件
            HSSFWorkbook workbook = new HSSFWorkbook();
            //创建sheet表单，默认名称为sheet1
            HSSFSheet sheet = workbook.CreateSheet("Fail to Import Data");


            //创建行，并设定第一行的表头
            HSSFRow rowTitle = sheet.CreateRow(0);

            rowTitle.CreateCell(0, HSSFCellType.STRING).SetCellValue("OrderNumber");
            rowTitle.CreateCell(1, HSSFCellType.STRING).SetCellValue("SiteID");
            rowTitle.CreateCell(2, HSSFCellType.STRING).SetCellValue("StoreID");
            rowTitle.CreateCell(3, HSSFCellType.STRING).SetCellValue("Fail Reason");


            int rowNum = 0;
            foreach (OrdersServiceReference.Orders temp in ErrList)
            {
                HSSFRow rowContent = sheet.CreateRow(rowNum + 1);//创建内容行

                //对第1行对应的单元格分别设定单元格内容属性和填充对应的值
                rowContent.CreateCell(0, HSSFCellType.STRING).SetCellValue(temp.OrderNumber);
                rowContent.CreateCell(1, HSSFCellType.STRING).SetCellValue(temp.SiteID);
                rowContent.CreateCell(2, HSSFCellType.STRING).SetCellValue(temp.StoreID.ToString());
                rowContent.CreateCell(3, HSSFCellType.STRING).SetCellValue(temp.Notes);
                rowNum++;//动态增加行号
            }

            //写入excel文件
            using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
            {
                workbook.Write(fs);//把流写入文件
            }

            MessageBox.Show(rowNum - 1 + "Item to Export");//实际导出的数据比定义的行号少1            
        }

        private void cbStore_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbStore.SelectedItem.ToString() != "")
            {
                SelectStore = true;
               
            }
            else
            {
                SelectStore = false;
            }

            if (SelectSite && SelectFile && SelectStore)
            {
                btnImport.Enabled = true;
            }
            else
            {
                btnImport.Enabled = false;
            }
        }
    }
}
